import { AT } from "../tool/at";
import { Note } from "../tool/note";
import { IVideoMeta } from "../tool/videometa";

const URL_BASE = 'https://ratemygirls.archive238.com';


const URL_EXIST_BV = `${URL_BASE}/api/bv/exist`;

export async function existBV(BVid: string): Promise<boolean> {
    const url = new URL(URL_EXIST_BV);
    url.searchParams.set('bvid', BVid);
    const result = await fetch(url.toString(), {
        method: 'GET',
    });
    const data = await result.json() as {
        exist: boolean;
    };
    return data.exist;
}

const URL_CREATE_BV = `${URL_BASE}/api/bv/create`;

export async function createBV(videoMeta: IVideoMeta) {
    const result = await fetch(URL_CREATE_BV, {
        method: 'POST',
        body: JSON.stringify({
            ...videoMeta,
        }),
    });
    return result.json();
}

const URL_GET_LATEST_COMMENT_DATE = `${URL_BASE}/api/comment/latestTimestamp`;

export async function getLatestCommentTimestamp(): Promise<number> {
    const result = await fetch(URL_GET_LATEST_COMMENT_DATE, {
        method: 'GET',
    });
    const data = await result.json() as {
        timestamp: string;
    };
    return parseInt(data.timestamp);
}


const URL_CREATE_COMMENT = `${URL_BASE}/api/comment/create`;

export async function createComment(at: AT, note: Note) {
    const result = await fetch(URL_CREATE_COMMENT, {
        method: 'POST',
        body: JSON.stringify({
            up: at.userbasic(),
            bvid: at.BV(),
            message: note.note,
            images: note.noteImages,
            commentTimestamp: at.timestamp(),
        }),
    });
    const data = await result.json() as unknown as {
        ok: boolean;
    };
    return data.ok;
}